package com.example.androidlearning.sy12.sy1localservice;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.androidlearning.R;

public class Sy1201_MainActivity extends AppCompatActivity {

    Button bind, unbind, stats;
    Sy1201_BindService.MyBinder binder;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("--Service Connected--");
            binder = (Sy1201_BindService.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("--Service Disconnected--");
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sy1201_main);

        init();
        setListener();
    }

    private void init() {

        bind = findViewById(R.id.sy12_bind);
        unbind = findViewById(R.id.sy12_unbind);
        stats = findViewById(R.id.sy12_getstatus);


    }

    private void setListener(){

        final Intent intent = new Intent(this, Sy1201_BindService.class);
        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bindService(intent, connection, Service.BIND_AUTO_CREATE);
            }
        });

        unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(connection);
            }
        });

        stats.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(Sy1201_MainActivity.this, "Service的count值为：" + binder.getCount(), Toast.LENGTH_LONG).show();
            }
        });

    }

}
